import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI, {Message} from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'

import routes from './routes'
import axios from 'axios'
import permission from './common/js/permission'
//@ 等价于 /src 这个目录，避免写麻烦又易错的相对路径
import '@/common/js/permission'

import BaiduMap from 'vue-baidu-map'

Vue.use(BaiduMap, {
    /* Visit http://lbsyun.baidu.com/apiconsole/key for details about app key. */
    ak: '4RWmQlKQkGgdOUuDqaVbkjBg2IY3sjh0'
})

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)
axios.defaults.baseURL = "http://127.0.0.1:8080/"
//自定义Vue对象属性
Vue.prototype.$http = axios
Vue.config.productionTip = false

const router = new VueRouter({
    routes
})

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res => {
    let token = localStorage.getItem("token");
    if (token) {
        res.headers["token"] = token;
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//


//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    if (false === res.data.success && "noLogin" === res.data.message) {
        localStorage.removeItem("token");
        localStorage.removeItem("loginInfo");
        localStorage.removeItem("menus");
        localStorage.removeItem("permissions");
        router.push({path: '/login'});
    }
    if (false === res.data.success && "noPermission" === res.data.message) {
        Message.warning('您没有访问权限')
    }
    if (false === res.data.success && "timeOut" === res.data.message) {
        localStorage.removeItem("token");
        localStorage.removeItem("loginInfo");
        localStorage.removeItem("menus");
        localStorage.removeItem("permissions");
        Message({"message":"登录时间过期，请重新登录!","type":"error"});
        router.push({path: '/login'});
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//


//======================路由的前端拦截器【拦截不到后端的请求】====================//
//注释掉登陆拦截：判断session中有没有user对象并且路径不是login就调转到登录页面
router.beforeEach((to, from, next) => {
    if (to.path == '/login' || to.path == "/register") {
        next();//放行
    } else {
        let logininfo = localStorage.getItem('loginInfo');
        if (logininfo) {
            next();
        } else {
            next({path: '/login'});//跳转到login
        }
    }
})

//处理页面刷新动态路由失效问题
initIndexRouters();

function initIndexRouters() {
    if (!localStorage.menus) {
        return;
    }
    //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
    if (router.options.routes.length > 5) {
        return;
    }
    // 获取本地登录用户的菜单
    let menus = localStorage.getItem('menus');
    // 将保存在本地的json字符串转化为json对象
    menus = JSON.parse(menus);
    let tempRouters = [];
    // 遍历当前用户所有的菜单
    menus.forEach(menu => {
        let indexRouter = {
            path: '/',
            iconCls: menu.icon,
            name: menu.name,
            component: resolve => require(['@/views/Home'], resolve),
            children: []
        }
        // 遍历所有子级菜单
        menu.children.forEach(cMenu => {
            let cr = {
                path: cMenu.url,
                name: cMenu.name,
                iconCls: cMenu.icon,
                component: resolve => require(['@/views/' + cMenu.component], resolve)
            }
            indexRouter.children.push(cr)
        })
        tempRouters.push(indexRouter)
        router.options.routes.push(indexRouter)
    })
    //动态路由配置
    router.addRoutes(tempRouters);
}

/*router.beforeEach((to, from, next) => {
    //NProgress.start();
    if (to.path == '/login') {
        sessionStorage.removeItem('user');
    }
    let user = JSON.parse(sessionStorage.getItem('user'));
    if (!user && to.path != '/login') {
        next({path: '/login'})
    } else {
        next()
    }
})*/

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
    //el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
}).$mount('#app')

